package com.hsy.dormmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hsy.dormmanage.common.result.Constants;
import com.hsy.dormmanage.common.result.Result;
import com.hsy.dormmanage.model.Administrator;
import com.hsy.dormmanage.model.Student;
import com.hsy.dormmanage.model.vo.LoginReturnVO;
import com.hsy.dormmanage.model.vo.LoginUser;
import com.hsy.dormmanage.service.AdministratorSer;
import com.hsy.dormmanage.service.StudentSer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;

/**
 * 包名:com.hsy.dormmanage.controller
 * 用户:86182
 * 时间:20211117:272021/11/16
 */
@Api(value = "登录")
@RestController
@RequestMapping("dorm")
public class LoginController {
    @Autowired
    private StudentSer studentSer;

    @Autowired
    private AdministratorSer adminSer;
    //登录
    @PostMapping(value = {"/","/login"})
    public Result login(HttpSession session,LoginUser loginUser){

        Student student = studentSer.queryById(loginUser.getId(), loginUser.getPwd());
        QueryWrapper<Administrator> wrapper = new QueryWrapper<>();
        wrapper.eq("id",loginUser.getId());
        wrapper.eq("pwd",loginUser.getPwd());
        Administrator administrator = adminSer.getOne(wrapper);

        if(student==null&&administrator==null){
            return Result.build(403,"用户名或密码错误");
        }else {
            if(administrator!=null){

                session.setAttribute(Constants.LOGIN_USER,administrator);

                LoginReturnVO loginReturnVO = new LoginReturnVO();
                loginReturnVO.setId(administrator.getId());
                loginReturnVO.setName(administrator.getName());
                String sessionId = session.getId();
                loginReturnVO.setToken(sessionId);

                return Result.ok(administrator);
            }else {
                session.setAttribute(Constants.LOGIN_USER,student);
                LoginReturnVO loginReturnVO = new LoginReturnVO();
                loginReturnVO.setId(student.getId());
                loginReturnVO.setName(student.getSname());
                String sessionId = session.getId();
                loginReturnVO.setToken(sessionId);
                return Result.ok(student);
            }
        }
    }
}
